package chapter04.deadLock.v2;

import lombok.extern.slf4j.Slf4j;

public class TestDeadLock {

    public static void main(String[] args) {
        Chopstick c1 = new Chopstick("1");
        Chopstick c2 = new Chopstick("2");
        Chopstick c3 = new Chopstick("3");
        Chopstick c4 = new Chopstick("4");
        Chopstick c5 = new Chopstick("5");

        new Philosopher("哲学家1",c1,c2).start();
        new Philosopher("哲学家2",c3,c2).start();
        new Philosopher("哲学家3",c3,c4).start();
        new Philosopher("哲学家4",c5,c4).start();
        new Philosopher("哲学家5",c1,c5).start();
    }

}

// 哲学家
@Slf4j
class Philosopher extends Thread{
    // 左筷子
    private Chopstick left;
    // 由筷子
    private Chopstick right;
    public Philosopher(String name,Chopstick left,Chopstick right){
        super(name);
        this.left=left;
        this.right=right;
    }

    @Override
    public void run() {
        while (true){
            // 尝试获取筷子
            synchronized (left){
                log.debug("get a chopstick：{}",left);
                synchronized (right){
                    log.debug("get a chopstick：{}",right);
                    eat();
                }
            }
        }
    }

    private void eat(){
        log.debug("eating...");
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}


// 筷子
class Chopstick{
    private String name;
    public Chopstick(String name){
        this.name=name;
    }

    @Override
    public String toString() {
        return "Chopstick{" +
                "name='" + name + '\'' +
                '}';
    }
}
